#pragma once
#include <iostream>
#include <sys/poll.h>
#include "Log.hpp"
#include "socket.hpp"

using namespace socket_ns;
static const int N = sizeof(fd_set) * 8;
static const int defaultfd = -1;
static const int gnum = 1000;


class PollServer
{
public:
    PollServer(int port)
        : _port(port), _listensocket(std::make_shared<TcpSocket>())
    {
        InetAddr local(port);
        _listensocket->BuildServerSocket(local);
        
        for(int i=0;i<gnum;i++)
        {
            _pof[i].fd=defaultfd;
            _pof[i].events=-1;
            _pof[i].events=-1;
        }
        _pof[0].fd=_listensocket->SockFd();
        _pof[0].events=POLLIN; 
        std::cout<<"haha"<<std::endl;
  }
    // listensockfd已经就绪
    void AcceptClient()
    {
        Log(DEBUG, "enter accpclient");
        InetAddr client;
        // 不会阻塞
        int sockfd = _listensocket->AcceptSocket(&client);
        if (sockfd < 0)
        {
            Log(ERROR, "accept error!");
            return;
        }
        // 连接已满
        else if (sockfd == N)
        {
            Log(ERROR, "当前浏览连接过多,连接sockfd:[%d], ip&&port: [%s:%d]已被强制关闭！", sockfd, client.IP().c_str(), client.port());
            close(sockfd);
        }
        // 正常添加
        else
        {
            for (int i = 1; i < gnum; i++)
            {
                if (_pof[i].fd == defaultfd)
                {
                    Log(DEBUG, "get a new link! sockfd:[%d], ip&&port: [%s:%d]", sockfd, client.IP().c_str(), client.port());
                    _pof[i].fd = sockfd;
                    _pof[i].events=POLLIN;
                    break;
                }
            }
        }
    }
    // readfd就绪
    void ServiceEcho(int pos)
    {

        char recvbuffer[1024];
        int n = recv(_pof[pos].fd, recvbuffer, sizeof(recvbuffer) - 1, 0);
        //std::cout << "recv end" << std::endl;
        if (n > 0)
        {
            recvbuffer[n] = 0;
            std::cout<<recvbuffer<<std::endl;
            std::string echostring = "Echo Server#";
            echostring += recvbuffer;
            send(_pof[pos].fd, echostring.c_str(), echostring.size(), 0);
        }
        else if (n == 0)
        {
            Log(ERROR, "%d connect alrady close!",_pof[pos].fd);
            close(_pof[pos].fd);
            _pof[pos].fd= defaultfd;
             _pof[pos].events=-1;
        }
        else
        {
            Log(ERROR, "%d recv error!", _pof[pos].fd);
            close(_pof[pos].fd);
            _pof[pos].fd = defaultfd;
            _pof[pos].events=-1;
        }
    }
    void HanderPoll()
    {
        std::cout<<"handerpool"<<std::endl;
        // 分为accept条件就绪与recvfd就绪
        for (int i = 0; i < gnum; i++)
        {
            if (_pof->fd == defaultfd)
            {
                continue;
            }
            int sockfd=_pof[i].fd;
            short revent=_pof[i].revents;
            if(revent=POLLIN)
            {
                if (sockfd == _listensocket->SockFd())
                {
                    AcceptClient();
                }
                else
                {
                    // std::cout << "serviceecho" << std::endl;
                    ServiceEcho(i);
                }
            }
        }
    }

    void start()
    {
        while (true)
        {
            sleep(1);
            int timeout=1000;
            int n = poll(_pof, gnum,timeout);
            switch (n)
            {
            case 0:
                Log(DEBUG, "poll 为0...");
                break;
            case -1:
                Log(DEBUG, "poll fail...");
                break;
            default: // 必然有就绪的fd
                Log(DEBUG, "enter hander");
                HanderPoll();
                break;
            }
        }
    }

    ~PollServer()
    {
    }

private:
    int _port;
    socket_ptr _listensocket;
    struct pollfd _pof[gnum];
};